import cv2
import numpy as np
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

frameWidth = 640
frameHeight = 480
nPlatesCascade = cv2.CascadeClassifier("Venv/Lib/site-packages/cv2/data/haarcascade_russian_plate_number.xml")
######

color = (255,0,255)
minArea = 500
count = 0

#######


img = cv2.imread('Resources/car111.jpg')
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
numberPlates = nPlatesCascade.detectMultiScale(imgGray, 1.1, 4)
for (x, y, w, h) in numberPlates:
    area = w*h
    if area>minArea:
        imgRoi1 = img[y:y + h, x:x + w]
        text = pytesseract.image_to_string(imgRoi1, config='--psm 11')
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)
        cv2.putText(img,text,(x,y-5),
                    cv2.FONT_HERSHEY_COMPLEX_SMALL,1,color,2)
        imgRoi = img[y:y+h,x:x+w]
        cv2.imshow('ROI',imgRoi)
        img_gray = cv2.cvtColor(imgRoi, cv2.COLOR_RGB2GRAY)
        img_gray_blur = cv2.medianBlur(imgRoi, 3)
        cv2.imshow("carplate_extract_img_gray_blur", img_gray_blur)
        text = pytesseract.image_to_string(img_gray_blur, config='--psm 11')
        print("Detected license plate Number is:", text)

cv2.imshow("Result", img)
cv2.waitKey(0)